﻿/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "UKeyUtils.h"
#include "../platform/Securec/securec.h"
#include "Global.h"

UKeyUtilsClass::UKeyUtils::UKeyUtils() {
}
UKeyUtilsClass::UKeyUtils::~UKeyUtils() {
}

/// <summary>
/// 使用私钥 解密 AES key 密文，默认：加密后密文的长度为 128， Key的长度为 16
/// </summary>
/// <param name="in">IN_OUT: 密文</param>
/// <param name="inLen">IN_OUT: 密文的长度</param>
void UKeyUtilsClass::UKeyUtils::DecryptAESKey(BYTE* data, DWORD& len) const
{
    HCRYPTPROV hCryptProv = NULL;
    if (!CryptAcquireContextA(&hCryptProv, "HAIER", CSP_NAME, PROV_RSA_FULL, 0)) {
        Global::ActionFailed(GetLastError());
        return;
    }

    HCRYPTKEY hKey;
    if (!CryptGetUserKey(hCryptProv, AT_KEYEXCHANGE, &hKey)) {
        Global::ActionFailed(GetLastError());
        CryptReleaseContext(hCryptProv, 0);
        return;
    }

    if (!CryptDecrypt(hKey, 0, TRUE, 1, data, &len)) {
        Global::ActionFailed(GetLastError());
        CryptReleaseContext(hCryptProv, 0);
        CryptDestroyKey(hKey);
        return;
    }

    CryptReleaseContext(hCryptProv, 0);
    CryptDestroyKey(hKey);
}
